var http = require('http')
var fs = require('fs')
var url = require('url')
var querystring = require('querystring')
http.createServer(function (resquest, response){
    if (resquest.url !== '/favicon.ico') {
        if (resquest.url === '/img') {
            response.writeHead(200, { 'Content-Type': 'image/jpeg' })
            // let img = fs.readFileSync('./img/img.jpg', 'binary') // 同步
            // response.write(img, 'binary')
            fs.readFile('./img/img.jpg', 'binary', function (err, res){
                err === true ? response.write(err, 'binary') : response.write(res, 'binary')
                response.end()
            })
        }else {
            response.writeHead(200, { 'Content-Type': 'text/html;charset=UTF-8' })
            let luYou = ''
            switch (resquest.url) {
                case '/' : {
                    luYou = fs.readFileSync('fs.html')
                    break
                }
                case '/login': {
                    luYou =  fs.readFileSync('./vive/login.html')
                    break
                }
                case '/reg': {
                    luYou = fs.readFileSync('./vive/reg.html')
                    break
                }
                default : {
                    luYou = fs.readFileSync('./vive/404.html')
                    break
                }
            }
            response.write(luYou)
            // GET
            //todo url模块处理get请求参数

            // let data = url.parse(resquest.url, true).query  // parse true 转换为对象的方法
            // console.log( data.name, data.password )

            //todo querystring + url模块处理get请求参数

            let data = url.parse(resquest.url).query
            console.log(querystring.parse(data).name, querystring.parse(data).password)

            // POST
            let ptData = ''
            resquest.on('data', (res)=>{
                ptData += res // 获取数据采用+=
            })
            resquest.on("end", ()=>{
                let isData = querystring.parse(ptData)
                console.log(
                    isData.name,
                    isData.password
                )
            })
            response.end()
        }
    }
}).listen(520)